package com.web.hotel.action;

import com.opensymphony.xwork2.ModelDriven;
import com.util.BaseActionUtil;
import com.util.DateUtil;
import com.util.JsonUtil;
import com.web.hotel.po.Dictionary;
import com.web.hotel.po.Hotel;
import com.web.hotel.po.Room;
import com.web.hotel.service.DictionaryService;
import com.web.hotel.service.HotelService;
import com.web.hotel.service.RoomService;
import org.apache.commons.io.IOUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Scope("prototype")
@ParentPackage(value = "struts-default")
@Namespace(value = "/")
@Action(value = "roomAction", results = {
        @Result(name = "index", location = "/jsp/hotel/room_list.jsp"),
        @Result(name = "addPage", location = "/jsp/hotel/room_add.jsp"),
})
public class RoomAction extends BaseActionUtil implements ModelDriven<Room> {
    private Room room;

    /**
     * 用于获取文件的数据流
     */
    private File[] picture;
    /**
     * 用于获取文件的文件名称(控件名称+FileName)
     */
    private String[] pictureFileName;
    /**
     * 用于获取文件的类型
     */
    private String[] pictureContentType;

    public File[] getPicture() {
        return picture;
    }

    public RoomAction setPicture(File[] picture) {
        this.picture = picture;
        return this;
    }

    public String[] getPictureFileName() {
        return pictureFileName;
    }

    public RoomAction setPictureFileName(String[] pictureFileName) {
        this.pictureFileName = pictureFileName;
        return this;
    }

    public String[] getPictureContentType() {
        return pictureContentType;
    }

    public RoomAction setPictureContentType(String[] pictureContentType) {
        this.pictureContentType = pictureContentType;
        return this;
    }

    @Resource(name = "roomService")
    private RoomService roomService;
    @Resource(name = "dictionaryService")
    private DictionaryService dictionaryService;
    @Resource(name = "hotelService")
    private HotelService hotelService;

    public String execute() throws Exception {
        return null;
    }

    public Room getModel() {
        room = new Room();
        return room;
    }

    public String index() {
        return "index";
    }

    public String addPage() {
        return "addPage";
    }

    public String listGrid() throws Exception {
        Map<String, Object> dataMap = roomService.listGrid(request);
        String jsonStr = JsonUtil.objectToStr(dataMap);
        System.out.println(jsonStr);
        out.print(jsonStr);
        out.flush();
        out.close();
        return NONE;
    }

    public String deleteRoomById() throws Exception {

        Map<String, Object> dataMap = new HashMap<String, Object>();

        String roomIds = request.getParameter("ids");
        if (roomIds == null || "".equals(roomIds)) {
            dataMap.put("flag", false);
            dataMap.put("msg", "服务端未接收到客户端传递的数据");
        } else {
            String[] roomIdList = roomIds.split(",");
            dataMap = roomService.deleteRoomById(roomIds);
        }
        String jsonStr = JsonUtil.objectToStr(dataMap);
        System.out.println(jsonStr);
        out.print(jsonStr);
        out.flush();
        out.close();
        return NONE;
    }

    public String addRoom() throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (room == null || "".equals(room)) {
            dataMap.put("flag", false);
            dataMap.put("msg", "服务端未接收到客户端传递的数据");
        } else {
            room.setRoomPicture(savePicture());
            room.setRoomStatus(0);
            dataMap = roomService.addRoom(room);
        }
        String jsonStr = JsonUtil.objectToStr(dataMap);
        System.out.println(jsonStr);
        out.print(jsonStr);
        out.flush();
        out.close();
        return NONE;
    }

    public String editRoom() throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (room == null || "".equals(room)) {
            dataMap.put("flag", false);
            dataMap.put("msg", "服务端未接收到客户端传递的数据");
        } else {
            Room roomi = roomService.getRoomById(room.getRoomId());
            String hotelId = request.getParameter("hotelId");
            Integer int_hotelId = new Integer(0);
            if (hotelId != null && !"".equals(hotelId)) {
                int_hotelId = Integer.parseInt(hotelId);
            }
            Hotel hotel = hotelService.getHotelById(int_hotelId);
            roomi.setHotel(hotel);
            roomi.setRoomPay(room.getRoomPay());
            roomi.setRoomDesc(room.getRoomDesc());
            roomi.setRoomType(room.getRoomType());
            roomi.setRoomName(room.getRoomName());
            room.setRoomPicture(savePicture());
            if (room.getRoomPicture() != null && !"".equals(room.getRoomPicture())) {
                roomi.setRoomPicture(room.getRoomPicture());
            }
            dataMap = roomService.editRoom(roomi);
        }
        String jsonStr = JsonUtil.objectToStr(dataMap);
        System.out.println(jsonStr);
        out.print(jsonStr);
        out.flush();
        out.close();
        return NONE;

    }

    public String getRoomById() throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        String roomId = request.getParameter("roomId");
        if (roomId == null || "".equals(roomId)) {
            dataMap.put("flag", false);
            dataMap.put("msg", "服务端未接收到客户端传递的数据 ");
        } else {
            Integer int_roomId = Integer.parseInt(roomId);
            Room roomI = roomService.getRoomById(int_roomId);
            dataMap.put("flag", true);
            dataMap.put("msg", roomI);
        }
        String jsonStr = JsonUtil.objectToStr(dataMap);
        System.out.println(jsonStr);
        out.print(jsonStr);
        out.flush();
        out.close();
        return NONE;
    }

    public String isExistArea() throws Exception {
        String roomName = request.getParameter("roomName");
        Room room = roomService.getRoomByRoomName(roomName);
        Boolean flag = true;
        if (room != null && !"".equals(room)) {
            flag = false;
        } else {
            flag = true;
        }
        String jsonStr = JsonUtil.objectToStr(flag);
        System.out.println(jsonStr);
        out.print(jsonStr);
        out.flush();
        out.close();
        return NONE;
    }

    public String getRoomType() throws Exception {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        //这里从字典树获取
        List<Dictionary> dictionaryList = dictionaryService.getDictionaryByDicName("sys_room_type");
        for (Dictionary dictionary : dictionaryList) {
            Map<String, Object> hotelType = new HashMap<String, Object>();
            hotelType.put("roomType", dictionary.getDicValue());
            result.add(hotelType);
        }
        String jsonStr = JsonUtil.objectToStr(result);
        System.out.println(jsonStr);
        out.print(jsonStr);
        out.flush();
        out.close();
        return NONE;
    }

    //文件保存到服务器上
    private String savePicture() throws IOException{
        /**
         * 服务器上的文件绝对路径
         */
        String ImagePath = "http://" + request.getServerName() //服务器地址
                + ":"
                + request.getServerPort()           //端口号
                + request.getContextPath()     //项目名称
                + "/image";
        String upload_filename = "";
        String upload_filepath = "";
        if (this.pictureFileName != null && !this.pictureFileName.equals("")) {
            for (int i = 0; i < picture.length; i++) {
                /**
                 * 获得文件输入流
                 */
                InputStream inputStream = new FileInputStream(this.picture[i]);
                /**
                 * 获取上传文件的的存放路径。
                 */
                String upload_path = this.servletContext.getRealPath("/image");
                /**
                 * 判断路径是否存在，不存在则创建文件夹
                 */
                File file = new File(upload_path);
                if (!file.exists()) {
                    file.mkdirs();
                }
                /**
                 * 防止文件重复修改文件名，加上日期
                 */
                upload_filepath = DateUtil.getTimeStamp() + "_" + this.pictureFileName[i];
                OutputStream outputStream = new FileOutputStream(upload_path + "/" + upload_filepath);
                int result = IOUtils.copy(inputStream, outputStream);
                IOUtils.closeQuietly(inputStream);
                IOUtils.closeQuietly(outputStream);
            }
        }
        return ImagePath + "/" + upload_filepath;
    }

}
